#Binary parser template

import os, sys
from Sanae3D.lib.ModelObject import Model3D
from Sanae3D.lib.StructReader import StructReader

class CityOfDreams_GCF(Model3D):
    '''Replace 'CityOfDreams_GCF' with a suitable name of your choice. Try to follow
    the standard: GameName_FormatExt'''
    
    def __init__(self, obj3D=None, outFile=None, inFile=None):
        
        super(CityOfDreams_GCF,self).__init__("XAC")
        self.obj3D = obj3D
        self.inFile = inFile
        self.outFile = outFile
        self.uvs = []
        self.faceUV = []
        
    def parse_material(self, filename):
        
        self.create_material(0)
        self.add_material_name(0, filename)
        self.add_texture_name(0, filename + ".tga")
        
    def parse_file(self):
        '''Main parser method. Can be replaced'''
        
        meshName = "obj"
        self.create_object(meshName)
        
        unk1 = self.inFile.read_long()
        print "count1", unk1
        for i in xrange(unk1):
            v1, v2, v3 = self.inFile.read_long(3)
            self.inFile.read_float(3)
            self.inFile.read_float(6)
            uv1, uv2, uv3 = self.inFile.read_long(3)
            
            self.create_face(meshName, i)
            self.add_face_verts(meshName, i, [v1-1, v2-1, v3-1])
            self.add_face_material(meshName, i, 0)
            #self.add_face_normals(meshName, i, [nx, ny, nz])
            self.faceUV.append([uv1 - 1, uv2 - 1, uv3 - 1])
            
            
        print self.inFile.tell()
        unk2 = self.inFile.read_long()
        print "count2", unk2
        
        for i in xrange(unk2):
            vx, vy, vz = self.inFile.read_float(3)
            self.create_vertex(meshName, i)
            self.add_coords(meshName, i, [vx, vy, vz])
            
        print self.inFile.tell()
        unk3 = self.inFile.read_long()
        print "unk3", unk3
        for i in xrange(unk3):
            tu, tv = self.inFile.read_float(2)
            self.uvs.append([tu, tv])
            
        for i in xrange(unk1):
            uv1, uv2, uv3 = self.faceUV[i]
            u1, v1 = self.uvs[uv1]
            u2, v2 = self.uvs[uv2]
            u3, v3 = self.uvs[uv3]
            self.add_face_uv(meshName, i, [u1, v1, u2, v2, u3, v3])
        
def read_file(path):
    '''Read the file'''
    
    filename, ext = os.path.splitext(os.path.basename(path))
    openFile = StructReader(open(path, 'rb'))
    obj = CityOfDreams_GCF(inFile=openFile)
    obj.parse_material(filename)
    obj.parse_file()
    openFile.close()
    return obj

def write_file(path):
    
    pass

def definitions():
    '''Return the header, extension, and a description of the format'''
    
    return "", "GCF", "City of Dreams GCF"

if __name__ == '__main__':
    
    file1 = ""
    obj = read_file(file1)